package com.music.ui.fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.music.R;
import com.music.application.Constants;
import com.music.entity.MusicInfo;
import com.music.entity.online.SearchMusic;
import com.music.loader.DataRequest;
import com.music.lrc.LyricAdapter;
import com.music.lrc.LyricLoadHelper;
import com.music.lrc.LyricSentence;
import com.music.utils.StringUtil;
import com.music.utils.ToastUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by dingfeng on 2016/4/16.
 */
public class LyricsFragment extends Fragment implements View.OnClickListener {

    private Context mContext;
    private ListView lyricshow;
    private TextView lyric_empty;
    private ImageView lyricErr;

    private LyricAdapter mLyricAdapter;
    private LyricLoadHelper mLyricLoadHelper;
    /**
     * 歌词是否正在下载
     */
    private boolean mIsLyricDownloading;

    private MusicInfo current;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        mContext = getActivity();
        Intent intent = getActivity().getIntent();
        current = intent.getParcelableExtra("current");
        mLyricLoadHelper = new LyricLoadHelper();
        mLyricLoadHelper.setLyricListener(mLyricListener);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View view = inflater.inflate(R.layout.fragment_lyrics, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        lyricshow = (ListView) view.findViewById(R.id.lyricshow);
        lyric_empty = (TextView) view.findViewById(R.id.lyric_empty);
        lyric_empty.setOnClickListener(this);
        mLyricAdapter = new LyricAdapter(mContext);
        lyricshow.setAdapter(mLyricAdapter);
        lyricshow.setEmptyView(lyric_empty);
        lyricErr = (ImageView) view.findViewById(R.id.lyricErr);
        lyricErr.setOnClickListener(this);
    }

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        loadLyric(current);
    }

    @Override
    public void onClick(View view) {
        // TODO Auto-generated method stub
        switch (view.getId()) {
            case R.id.lyric_empty:
                if (current == null) {
                    return;
                }
                loadLyricByHand();
                break;
            case R.id.lyricErr:
                showLyricTips();
                break;
        }
    }

    private LyricLoadHelper.LyricListener mLyricListener = new LyricLoadHelper.LyricListener() {

        @Override
        public void onLyricLoaded(List<LyricSentence> lyricSentences, int indexOfCurSentence) {
            // TODO Auto-generated method stub
            if (lyricSentences != null) {
                mLyricAdapter.setLyric(lyricSentences);
                mLyricAdapter.setCurrentSentenceIndex(indexOfCurSentence);
                mLyricAdapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onLyricSentenceChanged(int indexOfCurSentence) {
            // TODO Auto-generated method stub
            mLyricAdapter.setCurrentSentenceIndex(indexOfCurSentence);
            mLyricAdapter.notifyDataSetChanged();
            lyricshow.smoothScrollToPositionFromTop(indexOfCurSentence, lyricshow.getHeight() / 2, 500);
        }

    };


    /**
     * 歌词滚动
     *
     * @param millisecond
     */
    public void onProgress(long millisecond) {
        if (mLyricLoadHelper != null) {
            mLyricLoadHelper.notifyTime(millisecond);
        }
    }

    /**
     * 切换歌曲
     */
    public void onChange(MusicInfo current) {
        Log.d("dingfeng", "lyric fragment onChange...");
        this.current = current;
        mLyricAdapter.setLyric(new ArrayList<LyricSentence>());
        mLyricAdapter.setCurrentSentenceIndex(0);
        mLyricAdapter.notifyDataSetChanged();
        loadLyric(current);
    }

    /**
     * 加载歌词
     *
     * @param current
     */
    private void loadLyric(final MusicInfo current) {
        if (current == null) {
            return;
        }
        String lyricFilePath = Constants.LYRICPATH + current.getMusicName() + ".lrc";
        File lyricFile = new File(lyricFilePath);

        if (lyricFile.exists()) {
            mLyricLoadHelper.loadLyric(lyricFilePath);
        } else {
            mIsLyricDownloading = true;
            DataRequest.getInstance().getSearchResult(current.getMusicName(), current.getArtist(), new DataRequest.Callback<List<SearchMusic.SearchSong>>() {
                @Override
                public void onSuccess(List<SearchMusic.SearchSong> data) {
                    if (data != null) {
                        downloadLrc(current.getMusicName(), data.get(0).getSongId());
                    } else {
                        getLyricErr();
                    }
                }

                @Override
                public void onError(String err) {
                    getLyricErr();
                }
            });
        }
    }

    /**
     * 手动搜索
     */
    private void loadLyricByHand() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("歌词搜索");
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View dialog = inflater.inflate(R.layout.lry_search_dialog, null);
        final EditText artistEt = (EditText) dialog.findViewById(R.id.artist_tv);
        final EditText musicEt = (EditText) dialog.findViewById(R.id.music_tv);
        artistEt.setText(current.getArtist());
        musicEt.setText(current.getMusicName());

        builder.setView(dialog);
        builder.setNegativeButton(R.string.cancel, null);
        builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String artist = artistEt.getText().toString().trim();
                String music = musicEt.getText().toString().trim();
                if (TextUtils.isEmpty(artist) || TextUtils.isEmpty(music)) {
                    Toast.makeText(getActivity(), R.string.artist_music_null, Toast.LENGTH_SHORT).show();
                } else {
                    setLrc(music, artist);
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }

    private void setLrc(String title, String artist) {
        DataRequest.getInstance().getSearchResult(title, artist, new DataRequest.Callback<List<SearchMusic.SearchSong>>() {
            @Override
            public void onSuccess(List<SearchMusic.SearchSong> data) {
                if (data != null) {
                    downloadLrc(current.getMusicName(), data.get(0).getSongId());
                } else {
                    getLyricErr();
                }
            }

            @Override
            public void onError(String err) {
                getLyricErr();
            }
        });

    }

    private void downloadLrc(String title, long songId) {
        DataRequest.getInstance().getLrc(title, songId, new DataRequest.Callback<String>() {
            @Override
            public void onSuccess(String lrcPath) {
                if (StringUtil.isEmpty(lrcPath) || !new File(lrcPath).exists()) {
                    getLyricErr();
                } else {
                    mLyricLoadHelper.loadLyric(lrcPath);
                }
            }

            @Override
            public void onError(String err) {
                getLyricErr();
            }
        });
    }

    private void getLyricErr() {
        ToastUtil.showToast("获取歌词失败");
    }

    private void showLyricTips() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("提示");
        builder.setMessage("由于歌词直接从网络获取，可能与当前播放歌曲不一致，敬请谅解。");
        builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.show();
    }

}

